<!--
 * @Author: doing
 * @Date: 2023-08-10 10:21:19
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-02 21:20:39
 * @FilePath: \background-management-system\src\pages\video\index.vue
 * @Description: 
 * 视频管理页面
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->
<template>
    <div>
        <!-- 卡片视图区域 -->
        <el-card v-loading="isVideoListLoading">
            <!-- 实现表单模块 -->
            <el-form ref="searchRef" :model="searchForm" class="flex">
                <el-form-item label="视频名" class="mr-4" prop="title">
                    <el-input placeholder="请输入视频名" v-model="searchForm.title"></el-input>
                </el-form-item>
                <el-form-item label="类型：" class="mr-4" prop="type">
                    <el-select v-model="searchForm.type" clearable filterable style="width: 85px">
                        <el-option v-for="item in statusOptions" :key="item.code" :label="item.name" :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="findVideo" v-permission="['video:search']">
                    <el-icon style="vertical-align: middle;">
                        <search />
                    </el-icon>
                    <span style="vertical-align: middle;">查询</span>
                </el-button>
                <el-button @click="ressetForm">
                    <el-icon style="vertical-align: middle;">
                        <RefreshLeft />
                    </el-icon>
                    <span style="vertical-align: middle;">重置</span>
                </el-button>
                <el-button type="primary" @click="handleAdd" v-permission="['video:add']">
                    <el-icon style="vertical-align: middle;">
                        <CirclePlus />
                    </el-icon>
                    <span style="vertical-align: middle;">新增</span>
                </el-button>
            </el-form>

            <!-- 实现表格和分页 -->
                <el-table :data="videoList" border :table-layout="tableLayout" :cell-style="{ textAlign: 'center' }" :header-cell-style="{textAlign: 'center'}">
                    <el-table-column type="index" label="序号" porp="id"></el-table-column>
                    <el-table-column label="视频名" prop="title"></el-table-column>
                    <el-table-column label="视频" prop="coverUrl" min-width="130px">
                        <template #default="{ row }">
                            <el-image style="width: 100px; height: 100px" :src="row.coverUrl" :fit="fit">
                                <template #error>
                                    <div class="video-slot">
                                        <el-icon>
                                            <VideoCameraFilled />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="视频简介" prop="summary"></el-table-column>
                    <el-table-column label="用户昵称" prop="nickName"></el-table-column>
                    <el-table-column label="播放数" prop="playCount"></el-table-column>
                    <el-table-column label="点赞数" prop="thumhup"></el-table-column>
                    <el-table-column label="视频原名称" prop="videoOriginalName"></el-table-column>
                    <el-table-column label="类型" prop="type">
                        <template v-slot="scope">
                            <el-tag type="info" v-if="scope.row.type === 0">纪录片</el-tag>
                            <el-tag type="info" v-else-if="scope.row.type === 1">日常表演</el-tag>
                            <el-tag type="info" v-else-if="scope.row.type === 2">训练</el-tag>
                            <el-tag type="info" v-else>教学视频</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" prop="updateDate">
                        <template  #default="{ row }">
                            {{ formatTime(row.updateDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="auto" min-width="280px">
                        <template v-slot="scope">
                            <el-row :gutter="20" class="flex justify-center">
                                <el-button type="success" @click="handleEdit(scope.row)" icon="Edit" class="btn"
                                v-permission="['video:edit']"
                                >
                                    编辑
                                </el-button>
                                <el-button type="danger" @click="handleDelete(scope.row.id)" icon="Delete" class="btn"
                                v-permission="['video:detele']"
                                >
                                    删除
                                </el-button>
                            </el-row>
                        </template>
                    </el-table-column>
                </el-table>

            <el-pagination v-model:current-page="page.current" v-model:page-size="page.size"
                :page-sizes="[100, 200, 300, 400]" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />

        </el-card>

        <!-- 抽屉组件 -->
        <form-drawer ref="formDrawerRef" :title="drawerTitile" :destroyOnClose="true" @submit="drawerSubmit"
            @clean="cleanForm">
            <el-form :rules="rules" ref="formRef" :model="formDrawerData" label-width="100px" label-position="right"
                style="width: 400px">
                <el-form-item label="视频：" prop="videoUrl">
                    <!-- 上传视频 -->
                    <el-upload 
                        ref = "uploadRef"
                        class="avatar-uploader" 
                        action="" accept="video/*" 
                        :show-file-list="false"
                        :http-request="uploadMainVideo"
                        >
                        <video ref="videoRef" v-if="formDrawerData.videoUrl" :src="formDrawerData.videoUrl" class="avatar">
                            <canvas ref="canvasRef" class="canvasR"></canvas>
                            <img :src="videoThumbnail"/>
						</video>
                        <i v-else class="avatar-uploader-icon">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户图片：" prop="userImage">
                    <!-- 上传图片 -->
                    <el-upload class="avatar-uploader" action="" accept="image/*" :show-file-list="false" disabled>
                        <img v-if="formDrawerData.userImage" :src="formDrawerData.userImage" class="avatar">
                        <i v-else class="avatar-uploader-icon">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="视频名：" prop="title">
                    <el-input v-model="formDrawerData.title" />
                </el-form-item>
                <el-form-item label="用户名：" prop="nickName">
                    <el-input v-model="formDrawerData.nickName" disabled/>
                </el-form-item>
                <el-form-item label="视频简介" prop="summary">
                    <el-input v-model="formDrawerData.summary" />
                </el-form-item>
                <el-form-item label="播放数：" prop="playCount">
                    <el-input v-model="formDrawerData.playCount" />
                </el-form-item>
                <el-form-item label="点赞数：" prop="thumhup">
                    <el-input v-model="formDrawerData.thumhup" />
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="formDrawerData.type">
                        <el-radio :label="0">纪录片</el-radio>
                        <el-radio :label="1">日常表演</el-radio>
                        <el-radio :label="2">训练</el-radio>
                        <el-radio :label="3">教学视频</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </form-drawer>
    </div>
</template>
<script setup>
import { computed, ref, reactive, onMounted, nextTick  } from 'vue'
import FormDrawer from '~/components/FormDrawer.vue'
import {
    numberValidator
} from '~/composables/rule.js'
import {
    showModal,
    toast,
    formatTime
} from '~/composables/util.js'
import {
    getVideoList,
    addVideoList,
    deleteVideoList,
    updataVideoList,
    uploadVideo,
    getVideoUrl,
    deleteVideo,
} from '~/api/video.js'
import {
    deletePic,
    uploadPic
} from '~/api/picture.js'
import { useStore } from 'vuex'
//初始化数据开始
const store = useStore()
const fit = ref('contain')
const tableLayout = ref('fixed')
const isAddOrEdit = ref(true)
const isVideoListLoading = ref(false)
const drawerTitile = computed(() => isAddOrEdit.value ? '新增' : '修改')
const videoList = ref([])
const page = reactive({
    current: 1,
    size: 20,
    total :0
})

const Init = async function () {
    isVideoListLoading.value = true
    const body = { ...page,...searchForm }
    console.log('传递参数为')
    console.log(body)
    
    await getVideoList(body).then(res => {
        videoList.value = res.data.data.records
        console.log(videoList.value)
        page.total = res.data.data.total
    })
    isVideoListLoading.value = false
}


onMounted(() => {
    Init()
})

//初始化数据结束

//分页内容开始(待开发)
const disabled = ref(false)
const background = ref(true)

const handleSizeChange = async function () {
    Init()
}
const handleCurrentChange = function () {
    Init()
}
//分页内容结束

//操作栏开始
//删除操作
const handleDelete = function (id) {
    console.log(id)
    showModal('是否要删除该数据?').then(async () => {
        toast('正在删除中...', 'info', false, 3000)
        await deleteVideo(id).then(res => {
            toast('删除成功')
            //将页面引导到第一页
            ressetForm()
        }).catch(err=>{
            console.log(err)
        })
    })
}
//删除结束


//编辑开始
const formDrawerRef = ref(null)
const formRef = ref(null)
const formDrawerData = reactive({})
const videoRef = ref(null)
const oldVideoSourceId = ref('')  //编辑时候查询出来的那张照片
const oldImageUrl1 = ref('')
const videoThumbnail = ref('')
const isSubmit = ref(false)


//表单验证规则
const rules = {
    videoUrl: [
        { required: true, message: '请上传视频', trigger: 'blur' }
    ],
    title: [
        { required: true, message: '请输入视频名', trigger: 'blur' }
    ],
    summary: [
        { required: true, message: '请输入视频简介', trigger: 'blur' }
    ],
    playCount: [
        { required: true, validator: numberValidator, trigger: 'blur' }
    ],
    thumhup: [
        { required: true, validator: numberValidator, trigger: 'blur' }
    ]
}

//对视频截取第一帧的图片(baseURL)
const handleVideo = async () => {
    return new Promise((resolve,reject)=>{
        // let base64 = ''
        var video = document.querySelector(".avatar");
        video.setAttribute('crossOrigin', 'anonymous');//处理跨域
        video.setAttribute('src', formDrawerData.videoUrl);
        video.setAttribute('width', 400);
        video.setAttribute('height', 240);
        video.setAttribute('preload', 'auto');
        video.addEventListener('loadeddata',async function () {
            let canvas = document.createElement("canvas"),
            width = video.width, //canvas的尺寸和图片一样
            height = video.height;
            canvas.width = width;
            canvas.height = height;
            canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
            // base64 = canvas.toDataURL('image/jpeg'); //转换为base64
            await canvas.toBlob(function(blob) {
                resolve(blob);
            }, 'image/jpeg', 1);
        });
    })
};


//打开抽屉
const handleEdit = async function (item) {
    console.log(item)
    formDrawerRef.value.open()
    await getVideoUrl(item.videoSourceId).then(res=>{
        formDrawerData.videoUrl = res.data.data
    })
    await nextTick(()=>{
        isAddOrEdit.value = false
        
        formDrawerData.id = item.id
        formDrawerData.coverUrl = item.coverUrl
        formDrawerData.title = item.title
        formDrawerData.summary = item.summary
        formDrawerData.nickName = store.state.userList.nickName
        formDrawerData.userImage = store.state.userList.imageUrl
        formDrawerData.videoSourceId = item.videoSourceId
        formDrawerData.type = item.type
        formDrawerData.thumhup = item.thumhup
        formDrawerData.playCount = item.playCount

        //记录一下旧视频 和旧封面的地址
        oldVideoSourceId.value = item.videoSourceId
        oldImageUrl1.value = item.coverUrl
    })
}

//新增操作
const handleAdd = async function () {
    isAddOrEdit.value = true
    console.log(formDrawerData)

    formDrawerRef.value.open()
    formDrawerRef.value.hideLoading()

    await nextTick(()=>{
        delete formDrawerData.id
        delete formDrawerData.coverUrl
        delete formDrawerData.videoOriginalName
        delete formDrawerData.videoSourceId
        formDrawerData.nickName = store.state.userList.nickName
        formDrawerData.userImage = store.state.userList.imageUrl
        formDrawerData.type = 0
    })
}



// 删除视频
const deleteMainVideo = function (videoUrl) {
    // 发起请求进行删除视频
    deleteVideoList(videoUrl).then(res=>{
        console.log(res)
        toast('删除视频成功')
    })
}

//删除图片
const deleteMainPhoto = function(coverUrl){
    deletePic(coverUrl).then(res=>{
        console.log(res)
        toast('图片删除成功')
    })
}

// 上传视频, file 上传的视频对象
const uploadMainVideo = async function(file) {
    //创建表单结构
    console.log(file)
    const data = new FormData()
    data.append('file', file.file)
    toast('正在上传', 'info')
    
    //上传视频获取到videoSourceId
    await uploadVideo(data).then(res => {
        // 回显视频,使用url显示.
        formDrawerData.videoSourceId = res.data.data
        toast('上传成功')
        // formDrawerData.videoUrl = response.data
        // 将之前的视频删除，
        if(oldVideoSourceId.value !== '' || oldImageUrl1.value !== ''){
            //删除掉之前的视频和图片
            deleteMainVideo(oldVideoSourceId.value)
            deleteMainPhoto(oldImageUrl1.value)
        }
        //很重要
        oldVideoSourceId.value = res.data.data

    }).catch(error => {
        console.log(error)
        toast('上传失败', 'error')
    })
    
    //通过videoSourceId获取到对应的视频url
    await getVideoUrl(formDrawerData.videoSourceId).then(res=>{
        formDrawerData.videoUrl = res.data.data
        console.log(res)
    }).catch(error=>{
        console.log(error)
        toast('获取url失败','error')
    })

    nextTick(()=>{
        //将视频转化为blob,然后转化为FormData对象
        handleVideo().then(res=>{
            console.log(res)
            // 创建FormData对象并添加Blob数据
            var formData = new FormData();
            // 获取当前时间
            var currentTime = new Date().getTime();
            //添加数据到formData中
            formData.append('file', res, currentTime+'.jpg');
            //上传视频封面
            uploadPic(formData).then(res=>{
                //很重要
                oldImageUrl1.value = res.data.data
                formDrawerData.coverUrl = res.data.data
            })
        })  
    })        
}


//提交表单
const drawerSubmit = async () => {
    const data = {...formDrawerData}
    console.log('提交的数据为:')
    console.log(data)

    formRef.value.validate(async (valid) => {
        formDrawerRef.value.showLoading()
        if (!valid) {
            formDrawerRef.value.hideLoading()
            return false
        } else {
            formDrawerRef.value.showLoading()
            const fn = isAddOrEdit.value ? addVideoList(data) : updataVideoList(data)
            await fn
                .then(res => {
                    //后续可以加判断操作
                    console.log(res)
                    isSubmit.value = true
                    formDrawerRef.value.close()
                    toast(drawerTitile.value + '成功')
                    ressetForm()
                })
                .finally(() => {
                    isSubmit.value = false
                    formDrawerRef.value.hideLoading()
                })
        }
    })
}


//销毁该组件
const cleanForm = function () {
    console.log(formDrawerData)
    //针对添加时候传输上去的图片
    if(formDrawerData.videoSourceId && !isSubmit.value && isAddOrEdit.value){
        deleteMainVideo(formDrawerData.videoSourceId)
        deleteMainPhoto(formDrawerData.coverUrl)
    }

    formRef.value.resetFields()
}


//编辑结束

//操作栏结束


//查找按钮 重置按钮 新增按钮数据开始
const searchRef = ref(null)
const searchForm = reactive({})
const statusOptions = [
    { code: 0, name: '纪录片' },
    { code: 1, name: '日常表演' },
    { code: 2, name: '训练' },
    { code: 3, name: '教学视频' }
]
//查找操作
const findVideo = async function () {
    page.current = 1
    Init()
}
//重置操作
const ressetForm = function(){
    page.current = 1
    searchRef.value.resetFields()
    Init()
}

//查找按钮 重置按钮 新增按钮数据结束



//使用watch进行监听事件开始(开发进行检测作用)
// watch(form, (newVal, oldVal) => {
//     console.log(newVal)
// }, { immediate: true });
//使用watch进行监听事件结束
</script>
<style scoped>
.form {
    @apply flex justify-start items-center
}

.btn{
    margin: 0 10px;
}

.video-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}


.roleList-scrollbar {
    max-width: 600px;
    max-height: 160px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>